﻿using System;
using System.Data;
using System.Data.Common;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace SplendidCRM.Topics
{
    /// <summary>
    ///		Summary description for ListView.
    /// </summary>
    public partial class ListView : SplendidControl
    {
        protected _controls.ExportHeader ctlExportHeader;
        protected _controls.SearchView ctlSearchView;
        protected _controls.CheckAll ctlCheckAll;

        protected UniqueStringCollection arrSelectFields;
        protected DataView vwMain;
        protected SplendidGrid grdMain;
        protected Label lblError;

        protected void Page_Command(object sender, CommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Search")
                {
                    // 10/13/2005 Paul.  Make sure to clear the page index prior to applying search. 
                    grdMain.CurrentPageIndex = 0;
                    // 04/27/2008 Paul.  Sorting has been moved to the database to increase performance. 
                    grdMain.DataBind();
                }
                // 12/14/2007 Paul.  We need to capture the sort event from the SearchView. 
                else if (e.CommandName == "SortGrid")
                {
                    grdMain.SetSortFields(e.CommandArgument as string[]);
                    // 04/27/2008 Paul.  Sorting has been moved to the database to increase performance. 
                    // 03/17/2011 Paul.  We need to treat a comma-separated list of fields as an array. 
                    arrSelectFields.AddFields(grdMain.SortColumn);
                }
                // 11/17/2010 Paul.  Populate the hidden Selected field with all IDs. 
                else if (e.CommandName == "SelectAll")
                {
                    // 05/22/2011 Paul.  When using custom paging, vwMain may not be defined. 
                    if (vwMain == null)
                        grdMain.DataBind();
                    ctlCheckAll.SelectAll(vwMain, "ID");
                    grdMain.DataBind();
                }
            }
            catch (Exception ex)
            {
                SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                lblError.Text = ex.Message;
            }
        }

        // 09/08/2009 Paul.  Add support for custom paging. 
        protected void grdMain_OnSelectMethod(int nCurrentPageIndex, int nPageSize)
        {
            DbProviderFactory dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                con.Open();
                using (IDbCommand cmd = con.CreateCommand())
                {
                    string sTABLE_NAME = Crm.Modules.TableName(m_sMODULE);
                    cmd.CommandText = "  from vw" + sTABLE_NAME + "_List" + ControlChars.CrLf;
                    Security.Filter(cmd, m_sMODULE, "list");
                    ctlSearchView.SqlSearchClause(cmd);
                    cmd.CommandText = "select " + Sql.FormatSelectFields(arrSelectFields)
                                    + cmd.CommandText;
                    if (nPageSize > 0)
                    {
                        Sql.PageResults(cmd, sTABLE_NAME, grdMain.OrderByClause(), nCurrentPageIndex, nPageSize);
                    }
                    else
                    {
                        cmd.CommandText += grdMain.OrderByClause();
                    }

                    if (bDebug)
                        RegisterClientScriptBlock("SQLPaged", Sql.ClientScriptBlock(cmd));

                    // 01/13/2010 Paul.  Allow default search to be disabled. 
                    if (PrintView || IsPostBack || SplendidCRM.Crm.Modules.DefaultSearch(m_sMODULE))
                    {
                        using (DbDataAdapter da = dbf.CreateDataAdapter())
                        {
                            ((IDbDataAdapter)da).SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                da.Fill(dt);
                                // 11/22/2010 Paul.  Apply Business Rules. 
                                this.ApplyGridViewRules(m_sMODULE + "." + LayoutListView, dt);

                                vwMain = dt.DefaultView;
                                grdMain.DataSource = vwMain;
                            }
                        }
                        ctlExportHeader.Visible = true;
                    }
                    else
                    {
                        ctlExportHeader.Visible = false;
                    }
                }
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            SetPageTitle(L10n.Term(m_sMODULE + ".LBL_LIST_FORM_TITLE"));
            // 06/04/2006 Paul.  Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. 
            this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "list") >= 0);
            if (!this.Visible)
                return;

            try
            {
                // 09/08/2009 Paul.  Add support for custom paging in a DataGrid. Custom paging can be enabled / disabled per module. 
                if (Crm.Config.allow_custom_paging() && Crm.Modules.CustomPaging(m_sMODULE))
                {
                    // 10/05/2009 Paul.  We need to make sure to disable paging when exporting all. 
                    grdMain.AllowCustomPaging = (Request.Form[ctlExportHeader.ExportUniqueID] == null || ctlExportHeader.ExportRange != "All");
                    grdMain.SelectMethod += new SelectMethodHandler(grdMain_OnSelectMethod);
                    // 11/17/2010 Paul.  Disable Select All when using custom paging. 
                    ctlCheckAll.ShowSelectAll = false;
                }

                if (this.IsMobile && grdMain.Columns.Count > 0)
                    grdMain.Columns[0].Visible = false;
                DbProviderFactory dbf = DbProviderFactories.GetFactory();
                using (IDbConnection con = dbf.CreateConnection())
                {
                    con.Open();
                    using (IDbCommand cmd = con.CreateCommand())
                    {
                        grdMain.OrderByClause("NAME", "asc");

                        string sTABLE_NAME = Crm.Modules.TableName(m_sMODULE);
                        cmd.CommandText = "  from vw" + sTABLE_NAME + "_List" + ControlChars.CrLf;
                        Security.Filter(cmd, m_sMODULE, "list");
                        ctlSearchView.SqlSearchClause(cmd);
                        // 09/08/2009 Paul.  Custom paging will always require two queries, the first is to get the total number of rows. 
                        if (grdMain.AllowCustomPaging)
                        {
                            cmd.CommandText = "select count(*)" + ControlChars.CrLf
                                            + cmd.CommandText;

                            if (bDebug)
                                RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd));

                            // 01/13/2010 Paul.  Allow default search to be disabled. 
                            if (PrintView || IsPostBack || SplendidCRM.Crm.Modules.DefaultSearch(m_sMODULE))
                            {
                                grdMain.VirtualItemCount = Sql.ToInteger(cmd.ExecuteScalar());
                            }
                        }
                        else
                        {
                            // 04/27/2008 Paul.  The fields in the search clause need to be prepended after any Saved Search sort has been determined.
                            // 09/08/2009 Paul.  The order by clause is separate as it can change due to SearchViews. 
                            // 04/20/2011 Paul.  If there are no fields in the GridView.Export, then return all fields (*). 
                            cmd.CommandText = "select " + (Request.Form[ctlExportHeader.ExportUniqueID] != null ? SplendidDynamic.ExportGridColumns(m_sMODULE + ".Export") : Sql.FormatSelectFields(arrSelectFields))
                                            + cmd.CommandText
                                            + grdMain.OrderByClause();

                            if (bDebug)
                                RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd));

                            // 01/13/2010 Paul.  Allow default search to be disabled. 
                            if (PrintView || IsPostBack || SplendidCRM.Crm.Modules.DefaultSearch(m_sMODULE))
                            {
                                using (DbDataAdapter da = dbf.CreateDataAdapter())
                                {
                                    ((IDbDataAdapter)da).SelectCommand = cmd;
                                    using (DataTable dt = new DataTable())
                                    {
                                        da.Fill(dt);
                                        // 11/22/2010 Paul.  Apply Business Rules. 
                                        this.ApplyGridViewRules(m_sMODULE + "." + LayoutListView, dt);

                                        vwMain = dt.DefaultView;
                                        grdMain.DataSource = vwMain;
                                    }
                                }
                                ctlExportHeader.Visible = true;
                            }
                            else
                            {
                                ctlExportHeader.Visible = false;
                            }
                        }
                    }
                }
                if (!IsPostBack)
                {
                    // 06/09/2006 Paul.  Remove data binding in the user controls.  Binding is required, but only do so in the ASPX pages. 
                    //Page.DataBind();
                    // 09/08/2009 Paul.  Let the grid handle the differences between normal and custom paging. 
                    // 09/08/2009 Paul.  Bind outside of the existing connection so that a second connect would not get created. 
                    grdMain.DataBind();
                }
            }
            catch (Exception ex)
            {
                SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                lblError.Text = ex.Message;
            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            ctlSearchView.Command += new CommandEventHandler(Page_Command);
            ctlExportHeader.Command += new CommandEventHandler(Page_Command);
            ctlCheckAll.Command += new CommandEventHandler(Page_Command);
            // 11/26/2005 Paul.  Add fields early so that sort events will get called. 
            m_sMODULE = "Topics";
            // 02/13/2007 Paul.  Notes should highlight the Activities menu. 
            // 03/15/2011 Paul.  Change menu to use main module. 
            SetMenu(m_sMODULE);
            // 02/08/2008 Paul.  We need to build a list of the fields used by the search clause. 
            arrSelectFields = new UniqueStringCollection();
            arrSelectFields.Add("NAME");
            arrSelectFields.Add("DESCRIPTION");
            this.AppendGridColumns(grdMain, m_sMODULE + "." + LayoutListView, arrSelectFields);
        }
        #endregion
    }
}